import { lazy, ReactElement, Suspense } from 'react'
import { createBrowserRouter, Navigate, redirect, RouteObject, useRouteError } from 'react-router-dom'
import { Flex, Spin } from 'antd'
import { getItem, getUrlSearchParams, message, PERMISSIONROUTERLIST, setItem, TOKEN } from '@hs-admin/utils'
import Home from '@/views/Home/Home.tsx'
import DataOperate from '@/views/Home/DataOperate/DataOperate.tsx'
import DataProduce from '@/views/Home/DataProduce/DataProduce.tsx'
import DataProperty from '@/views/Home/DataProperty/DataProperty.tsx'
import Demo from '@/views/Demo/Demo.tsx'
import Layout from '@/views/Layout'
import { login } from '@/api/login.ts'

const Login = lazy(() => import('@/views/Login'))

function withLoading(component: ReactElement) {
  return <Suspense fallback={<Spin />}>{component}</Suspense>
}

function ErrorBoundary() {
  const error = useRouteError() as {
    message?: string
    status?: number
  }
  let text = ''
  if (error.message?.includes('Failed to fetch dynamically imported module')) {
    text = '页面已发新版，请强刷页面或清空缓存'
  } else if (error.message?.length) {
    text = error.message
  } else if (error.status === 404) {
    text = '页面不存在'
  } else if (error.status === 403) {
    text = '您没有该页面权限'
  } else {
    text = '未知错误'
    console.error(error)
  }
  return (
    <Flex align="center" justify="center" style={{ height: '100%' }}>
      <h1>{text}</h1>
    </Flex>
  )
}

const privateRouter: RouteObject[] = [
  {
    path: '',
    element: withLoading(<Navigate to="/home" replace />),
    loader: () => {
      const permissions = getItem(PERMISSIONROUTERLIST)
      if (Array.isArray(permissions)) {
        if (permissions) {
          return redirect('/home')
        }
      }
      return null
    }
  },
  {
    path: 'home',
    element: withLoading(<Home />)
  },
  {
    path: 'home/DataOperate',
    element: withLoading(<DataOperate />)
  },
  {
    path: 'home/DataProduce',
    element: withLoading(<DataProduce />)
  },
  {
    path: 'home/DataProperty',
    element: withLoading(<DataProperty />)
  },
  {
    path: '/Demo',
    element: withLoading(<Demo />)
  }
]

const routeConfig: RouteObject[] = [
  {
    path: '/',
    element: withLoading(<Layout />),
    children: privateRouter,
    loader: async () => {
      const token = getItem(TOKEN)
      if (!token) {
        return redirect('/login')
      }
      return null
      // // 校验跳转路由是否有权限
      // const configMenuList = getItem(PERMISSIONROUTERLIST) || []
      // const _isPass = configMenuList.some((item: string) => request.url.includes(item))
      // if (_isPass) {
      //   return null
      // } else {
      //   return redirect(configMenuList[0])
      // }
    }
  },
  {
    path: '/login',
    element: withLoading(<Login />),
    loader: async ({ request }) => {
      const code = getUrlSearchParams('code', request.url)
      if (code) {
        const res = await login({ code })
        setItem(TOKEN, res.access_token)
        return redirect('/')
      } else {
        return null
      }
    },
    errorElement: <ErrorBoundary />
  }
]

const router = createBrowserRouter(routeConfig)

// Clean up on module reload (HMR)
// https://vitejs.dev/guide/api-hmr
if (import.meta.hot) {
  import.meta.hot.dispose(() => router.dispose())
}

export default router
